#!/bin/bash

: '

官方的安装脚本：
https://gitee.com/bnu_mixly/mixly3.0-linux-arm64/raw/master/一键更新.sh

'

SWNAME=mixly
DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
app_dir=/opt/apps/${SWNAME}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh


function sw_download() {
	case "${CURRENT_VM_ARCH}" in
		"arm64")
				apt-get install -y git
				exit_if_fail $? "git安装失败"


				echo "正在克隆 Electron 运行时"
				swDIR="${app_dir}"
				swUrl="https://gitee.com/bnu_mixly/mixly3.0-linux-arm64.git"
				download_file3 "${swDIR}" "${swUrl}"
				exit_if_fail $? "下载失败，网址：${swUrl}"

				echo "正在克隆主程序, ref to: .gitmodules"
				swDIR="${app_dir}/resources/app/src"
				rm -rf ${swDIR}
				swUrl="https://gitee.com/bnu_mixly/mixly3.git"
				download_file3 "${swDIR}" "${swUrl}"
				exit_if_fail $? "下载失败，网址：${swUrl}"


				# ================= 各芯片平台的文件 =================
				for swUrl in \
				"https://gitee.com/bnu_mixly/linux-avr-arm64.git" \
				"https://gitee.com/mixly2/arduino-libs.git" \
				"https://gitee.com/bnu_mixly/linux_esp8266_arm64.git" \
				"https://gitee.com/bnu_mixly/linux_esp32_arm64.git" \
				;
				do
					platforms=`basename ${swUrl}`
					echo "正在克隆 ${platforms} 硬件相关的文件"
					swDIR="${app_dir}/hw_platforms/${platforms}"
					download_file3 "${swDIR}" "${swUrl}"
					exit_if_fail $? "下载失败，网址：${swUrl}"

					cp -a "$swDIR/." "$app_dir"
					# exit_if_fail $? "文件复制失败: ${platforms}"
				done
				;;
		*) exit_unsupport ;;
	esac

}

function sw_install() {
	chmod a+x /opt/apps/mixly/arduino-cli/arduino-cli
	chmod a+x /opt/apps/mixly/arduino-cli/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/*
}

function sw_create_desktop_file() {
	cat <<- EOF > ${DSK_PATH}
		[Desktop Entry]
		Encoding=UTF-8
		Version=0.9.4
		Type=Application
		Name=mixly
		Terminal=false
		Icon=${app_dir}/resources/app/src/files/mixly.icns
		Categories=System;
		Exec=${app_dir}/Mixly --no-sandbox %f
	EOF
	cp2desktop ${DSK_PATH}
}

if [ "${action}" == "卸载" ]; then
	rm -rf ${app_dir}
	rm2desktop ${DSK_FILE}
else
	sw_download
	sw_install
	sw_create_desktop_file
fi


